<template>
  <div class="commodity-system-container">
    <!-- 搜索表单 -->
    <div class="search-form">
      <el-form :model="searchData" :inline="true">
        <el-form-item label="商品名称">
          <el-input
            v-model="searchData.productName"
            placeholder="请输入商品名称"
            style="width: 200px"
            clearable
          />
        </el-form-item>
        <el-form-item label="商品ID">
          <el-input
            v-model="searchData.productId"
            placeholder="请输入商品ID"
            style="width: 200px"
            clearable
          />
        </el-form-item>
        <el-form-item label="商家名称">
          <el-input
            v-model="searchData.shopName"
            placeholder="请输入商家名称"
            style="width: 200px"
            clearable
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-select
            v-model="searchData.shelveState"
            placeholder="请选择状态"
            style="width: 120px"
            clearable
          >
            <el-option label="已上架" :value="1" />
            <el-option label="已下架" :value="0" />
            <el-option label="待审核" :value="2" />
            <el-option label="审核失败" :value="3" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
          <el-button type="success" @click="handleExport">导出</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 商品表格 -->
    <art-table
      :data="tableData"
      :loading="loading"
      :pagination="true"
      :total="total"
      :current-page="searchData.page"
      :page-size="searchData.pageSize"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      highlight-current-row
      show-header-background
    >
      <el-table-column prop="productId" label="商品ID" min-width="100" />
      <el-table-column prop="image" label="商品主图" min-width="120">
        <template #default="scope">
          <el-image
            :src="scope.row.image"
            class="product-image"
            fit="cover"
            lazy
            :preview-src-list="[scope.row.image]"
            preview-teleported
          />
        </template>
      </el-table-column>
      <el-table-column prop="productName" label="商品名称" min-width="200" />
      <el-table-column prop="shopName" label="商家名称" min-width="150" />
      <el-table-column prop="sectionPrice" label="售价区间" min-width="150">
        <template #default="scope">
          <span v-if="scope.row.sectionPrice">{{ scope.row.sectionPrice }}</span>
          <span v-else-if="scope.row.price">¥{{ scope.row.price }}</span>
          <span v-else>暂无</span>
        </template>
      </el-table-column>
      <el-table-column prop="stockNumber" label="库存" min-width="100" align="center" />
      <el-table-column prop="volume" label="实际销量" min-width="100" align="center" />
      <el-table-column prop="fictitiousNumber" label="虚拟销量" min-width="100" align="center" />
      <el-table-column prop="createTime" label="创建时间" min-width="180" />
      <el-table-column label="上架状态" min-width="100" align="center">
        <template #default="scope">
          <el-tag v-if="scope.row.shelveState === 1" type="success">已上架</el-tag>
          <el-tag v-else-if="scope.row.shelveState === 0" type="info">已下架</el-tag>
          <el-tag v-else-if="scope.row.shelveState === 2" type="warning">待审核</el-tag>
          <el-tag v-else-if="scope.row.shelveState === 3" type="danger">审核失败</el-tag>
          <el-tag v-else>未知</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="100" fixed="right">
        <template #default="scope">
          <div class="table-actions">
            <el-button link type="primary" @click="handleView(scope.row)">查看</el-button>

            <!-- 待审核状态显示审核按钮 -->
            <el-button
              v-if="scope.row.shelveState === 2"
              link
              type="primary"
              @click="handleExamine(scope.row)"
            >
              审核
            </el-button>

            <!-- 已上架商品显示强制下架按钮 -->
            <el-button
              v-if="scope.row.shelveState === 1"
              link
              type="primary"
              @click="handleForceOffShelf(scope.row)"
            >
              强制下架
            </el-button>

            <!-- 已上架商品显示虚拟销量编辑按钮 -->
            <el-button
              v-if="scope.row.shelveState === 1"
              link
              type="primary"
              @click="handleEditVirtualSales(scope.row)"
            >
              虚拟销量
            </el-button>
          </div>
        </template>
      </el-table-column>
    </art-table>
    <!-- 分页组件专用滚动容器 -->
    <div class="pagination-scroll-wrapper">
      <!-- 分页组件内容会通过ArtTable组件渲染在这里 -->
    </div>

    <!-- 审核对话框 -->
    <el-dialog
      v-model="examineDialogVisible"
      title="商品审核"
      width="40%"
      center
      :close-on-click-modal="false"
    >
      <el-form
        ref="examineFormRef"
        :model="examineForm"
        :rules="examineFormRules"
        label-width="100px"
      >
        <el-form-item label="审核结果" prop="state">
          <el-radio-group v-model="examineForm.state">
            <el-radio :label="1">通过</el-radio>
            <el-radio :label="2">不通过</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="examineForm.state === 2" label="不通过原因" prop="reason">
          <el-input
            v-model="examineForm.reason"
            type="textarea"
            :rows="4"
            placeholder="请输入审核不通过的原因"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="examineDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitExamine">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 商品详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="商品详情"
      width="60%"
      center
      :close-on-click-modal="false"
    >
      <div class="product-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="商品名称">{{
            currentProduct.productName
          }}</el-descriptions-item>
          <el-descriptions-item label="官方分类">{{
            currentProduct.classifyName
          }}</el-descriptions-item>
          <el-descriptions-item label="商品卖点">{{
            currentProduct.productBrief
          }}</el-descriptions-item>
          <el-descriptions-item label="商家分组">{{
            currentProduct.shopGroupName
          }}</el-descriptions-item>
          <el-descriptions-item label="商家名称">{{
            currentProduct.shopName
          }}</el-descriptions-item>
          <el-descriptions-item label="商品状态">
            <el-tag v-if="currentProduct.shelveState === 1" type="success">已上架</el-tag>
            <el-tag v-else-if="currentProduct.shelveState === 0" type="info">已下架</el-tag>
            <el-tag v-else-if="currentProduct.shelveState === 2" type="warning">待审核</el-tag>
            <el-tag v-else-if="currentProduct.shelveState === 3" type="danger">审核失败</el-tag>
            <el-tag v-else>未知</el-tag>
          </el-descriptions-item>
        </el-descriptions>

        <div
          class="product-images"
          v-if="currentProduct.images && currentProduct.images.length > 0"
        >
          <div class="image-label">商品图片:</div>
          <div class="image-list">
            <el-image
              v-for="(item, index) in currentProduct.images"
              :key="index"
              class="pro-image"
              :src="item.imgPath"
              fit="cover"
              :preview-src-list="currentProduct.images?.map((img: any) => img.imgPath)"
              preview-teleported
              @click="handlePictureCardPreview(item)"
            />
          </div>
        </div>

        <div class="sku-table" v-if="currentProduct.skus && currentProduct.skus.length > 0">
          <div class="sku-label">商品款式:</div>
          <el-table
            :data="currentProduct.skus"
            style="width: 100%"
            :header-cell-style="{
              background: 'var(--art-gray-50)',
              color: 'var(--art-text-color-primary)'
            }"
          >
            <el-table-column
              v-for="(skuAttr, index) in currentProduct.names"
              :key="index"
              :label="skuAttr.skuName"
            >
              <template #default="scope">
                {{
                  getSkuAttrValue(
                    scope.row.skuAttrCodeDTOList && scope.row.skuAttrCodeDTOList[index],
                    currentProduct.names
                  )
                }}
              </template>
            </el-table-column>
            <el-table-column label="售价" prop="price" />
            <el-table-column label="原价" prop="originalPrice" />
            <el-table-column label="库存" prop="stockNumber" />
            <el-table-column label="重量(KG)" prop="weight" />
            <el-table-column label="SKU" prop="sku" />
          </el-table>
        </div>

        <div class="product-text" v-if="currentProduct.productText">
          <div class="text-label">商品简介:</div>
          <div class="text-content" v-html="currentProduct.productText"></div>
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 图片预览对话框 -->
    <el-dialog
      v-model="imagePreviewVisible"
      append-to-body
      class="check-image-dialog"
      title="查看图片"
      center
    >
      <img
        :src="previewImageUrl"
        style="display: block; margin: auto; max-width: 500px; max-height: 500px"
        alt="预览图片"
      />
    </el-dialog>

    <!-- 虚拟销量编辑对话框 -->
    <el-dialog
      v-model="virtualSalesDialogVisible"
      title="编辑虚拟销量"
      width="30%"
      center
      :close-on-click-modal="false"
    >
      <el-form ref="virtualSalesFormRef" :model="virtualSalesForm" label-width="100px">
        <el-form-item label="当前虚拟销量">
          <span>{{ virtualSalesForm.currentVirtualSales }}</span>
        </el-form-item>
        <el-form-item label="调整方式" prop="adjustType">
          <el-radio-group v-model="virtualSalesForm.adjustType">
            <el-radio :label="1">增加</el-radio>
            <el-radio :label="2">减少</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="调整数量" prop="adjustValue">
          <el-input-number
            v-model="virtualSalesForm.adjustValue"
            :min="0"
            controls-position="right"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="virtualSalesDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitVirtualSales">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
  import { ref, reactive, onMounted } from 'vue'
  import { ElMessage } from 'element-plus'
  import type { FormInstance } from 'element-plus'
  import {
    getCommodityList,
    examineCommodity,
    forceOffShelf,
    exportCommodity,
    setFictitious,
    getCommodityById
  } from '@/api/commodityApi'
  import { getCommodityClassList as fetchCommodityClassList } from '@/api/commodityClassApi'
  import { ApiStatus } from '@/utils/http/status'
  import type { CommodityType } from '@/api/model/commodityModel.ts'

  // 搜索数据
  const searchData = reactive({
    productName: '',
    productId: '',
    shopName: '',
    shelveState: undefined,
    page: 1,
    pageSize: 10 // 减少初始页面大小以提高加载速度
  })

  // 表格数据
  const tableData = ref<CommodityType[]>([])
  const total = ref(0)
  const loading = ref(false)

  // 商品类别选项
  const classifyOptions = ref<{ classifyId: number; classifyName: string }[]>([])

  // 审核表单
  const examineFormRef = ref<FormInstance | null>(null)
  const examineDialogVisible = ref(false)
  const examineForm = reactive({
    productId: 0,
    shelveState: 1,
    reason: ''
  })

  const examineFormRules = {
    reason: [
      {
        required: true,
        message: '请输入审核不通过的原因',
        trigger: 'blur'
      }
    ]
  }

  // 商品详情
  const detailDialogVisible = ref(false)
  const currentProduct = ref<CommodityType>({})

  // 图片预览
  const imagePreviewVisible = ref(false)
  const previewImageUrl = ref('')

  // 虚拟销量编辑表单
  const virtualSalesDialogVisible = ref(false)
  const virtualSalesFormRef = ref<FormInstance | null>(null)
  const virtualSalesForm = reactive({
    productId: 0,
    currentVirtualSales: 0,
    adjustType: 1, // 1: 增加, 2: 减少
    adjustValue: 0
  })

  // 初始化数据
  onMounted(() => {
    // 并行加载数据以提高性能
    Promise.all([getCommodityListData(), loadCommodityClassList()]).catch((error) => {
      console.error('数据加载失败:', error)
    })
  })

  // 获取商品列表
  const getCommodityListData = async () => {
    loading.value = true
    try {
      const res = await getCommodityList(searchData)
      if (res.code === ApiStatus.success) {
        tableData.value = res.data.list || []
        total.value = res.data.total || 0
      } else {
        ElMessage.error(res.message || '获取商品列表失败')
        tableData.value = []
        total.value = 0
      }
    } catch (error) {
      ElMessage.error('获取商品列表失败')
      console.error(error)
      tableData.value = []
      total.value = 0
    } finally {
      loading.value = false
    }
  }

  // 获取商品类别列表
  const loadCommodityClassList = async () => {
    try {
      const res = await fetchCommodityClassList({ page: 1, pageSize: 100 }) // 减少获取的数量
      if (res.code === ApiStatus.success) {
        // 确保classifyId和classifyName存在
        classifyOptions.value = (res.data.list || [])
          .filter((item) => item.classifyId !== undefined && item.classifyName !== undefined)
          .map((item) => ({
            classifyId: item.classifyId as number,
            classifyName: item.classifyName as string
          }))
      } else {
        ElMessage.error(res.message || '获取商品类别失败')
      }
    } catch (error) {
      ElMessage.error('获取商品类别失败')
      console.error(error)
    }
  }

  // 处理搜索
  const handleSearch = () => {
    searchData.page = 1
    getCommodityListData()
  }

  // 处理重置
  const handleReset = () => {
    searchData.productName = ''
    searchData.shelveState = undefined
    searchData.page = 1
    searchData.pageSize = 10
    getCommodityListData()
  }

  // 处理分页大小变化
  const handleSizeChange = (size: number) => {
    searchData.pageSize = size
    getCommodityListData()
  }

  // 处理当前页变化
  const handleCurrentChange = (current: number) => {
    searchData.page = current
    getCommodityListData()
  }

  // 查看商品详情
  const handleView = (row: CommodityType) => {
    if (!row.productId) {
      ElMessage.error('商品ID无效')
      return
    }

    // 获取完整的商品详情信息
    getCommodityById({ productId: row.productId })
      .then((res) => {
        if (res.code === ApiStatus.success) {
          currentProduct.value = res.data || {}
          detailDialogVisible.value = true
        } else {
          ElMessage.error(res.message || '获取商品详情失败')
        }
      })
      .catch((error) => {
        ElMessage.error('获取商品详情失败')
        console.error(error)
      })
  }

  // 图片预览处理
  const handlePictureCardPreview = (item: any) => {
    previewImageUrl.value = item.imgPath
    imagePreviewVisible.value = true
  }

  // 获取SKU属性值
  const getSkuAttrValue = (map: any, list: any) => {
    if (!map) {
      return ''
    }

    const hasChilds =
      list &&
      list.filter((skuAttr: any) => {
        const hasChild =
          skuAttr.values &&
          skuAttr.values.some((attr: any) => {
            return attr.skuValue
          })
        return skuAttr.skuName && hasChild
      })

    const { code, valueCode } = map
    let codeStr = ''

    if (hasChilds) {
      hasChilds.map((item: any) => {
        const { values } = item
        if (values) {
          values.some((attr: any) => {
            if (attr.skuCode === code || attr.skuCode === valueCode) {
              codeStr = attr.skuValue
              return true
            }
            return false
          })
        }
      })
    }

    return codeStr
  }

  // 强制下架商品
  const handleForceOffShelf = async (row: CommodityType) => {
    if (!row.productId) return

    try {
      // 显示确认对话框
      await ElMessageBox.confirm('确认要强制下架该商品吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })

      const res = await forceOffShelf({ productId: row.productId })
      if (res.code === ApiStatus.success) {
        ElMessage.success('强制下架成功')
        getCommodityListData()
      } else {
        ElMessage.error(res.message || '强制下架失败')
      }
    } catch (error) {
      // 用户取消操作不显示错误信息
      if (error !== 'cancel' && error !== 'close') {
        ElMessage.error('强制下架失败')
        console.error(error)
      }
    }
  }

  // 处理审核
  const handleExamine = (row: CommodityType) => {
    if (!row.productId) return

    examineForm.productId = row.productId
    examineForm.shelveState = 1
    examineForm.reason = ''
    examineDialogVisible.value = true
  }

  // 提交审核
  const submitExamine = async () => {
    if (!examineFormRef.value) return

    try {
      await examineFormRef.value.validate()

      const res = await examineCommodity({
          productId: examineForm.productId,
          shelveState: examineForm.shelveState,
          reason: examineForm.shelveState === 2 ? examineForm.reason : undefined
        })

      if (res.code === ApiStatus.success) {
        ElMessage.success('审核操作成功')
        examineDialogVisible.value = false
        getCommodityListData()
      } else {
        ElMessage.error(res.message || '审核操作失败')
      }
    } catch (error) {
      console.error(error)
    }
  }

  // 处理编辑虚拟销量
  const handleEditVirtualSales = (row: CommodityType) => {
    if (!row.productId) return

    virtualSalesForm.productId = row.productId
    virtualSalesForm.currentVirtualSales = row.fictitiousNumber || 0
    virtualSalesForm.adjustType = 1
    virtualSalesForm.adjustValue = 0
    virtualSalesDialogVisible.value = true
  }

  // 提交虚拟销量调整
  const submitVirtualSales = async () => {
    if (!virtualSalesFormRef.value || !virtualSalesForm.productId) return

    try {
      // 计算新的虚拟销量
      let newVirtualSales = virtualSalesForm.currentVirtualSales
      if (virtualSalesForm.adjustType === 1) {
        // 增加
        newVirtualSales += virtualSalesForm.adjustValue
      } else {
        // 减少
        newVirtualSales -= virtualSalesForm.adjustValue
        // 确保不会小于0
        newVirtualSales = Math.max(0, newVirtualSales)
      }

      // 调用API更新虚拟销量
      const res = await setFictitious({
        productId: virtualSalesForm.productId,
        fictitiousNumber: newVirtualSales
      })

      if (res.code === ApiStatus.success) {
        ElMessage.success('虚拟销量更新成功')
        virtualSalesDialogVisible.value = false
        getCommodityListData()
      } else {
        ElMessage.error(res.message || '虚拟销量更新失败')
      }
    } catch (error) {
      ElMessage.error('虚拟销量更新失败')
      console.error(error)
    }
  }

  // 导出商品
  const handleExport = async () => {
    try {
      const res = await exportCommodity(searchData)
      // 创建下载链接
      const blob = new Blob([res])
      const url = window.URL.createObjectURL(blob)
      const link = document.createElement('a')
      link.href = url
      link.download = '商品列表.xlsx'
      link.click()
      window.URL.revokeObjectURL(url)
      ElMessage.success('导出成功')
    } catch (error) {
      ElMessage.error('导出失败')
      console.error(error)
    }
  }
</script>

<style lang="scss" scoped>
  .commodity-system-container {
    padding: 20px;

    .search-form {
      padding: 15px;
      margin-bottom: 20px;
      background-color: var(--art-gray-50);
      border-radius: 4px;
    }

    .product-info {
      display: flex;
      align-items: center;

      .product-image {
        flex-shrink: 0; /* 防止图片压缩 */
        width: 50px;
        height: 50px;
        margin-right: 10px;
        border-radius: 4px;
      }

      .product-name {
        flex: 1;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
    }

    .table-actions {
      display: flex;
      flex-wrap: wrap;
      gap: 10px;
    }

    .dialog-footer {
      display: flex;
      gap: 10px;
      justify-content: flex-end;
    }

    .product-detail {
      .image-label,
      .sku-label,
      .text-label {
        margin: 15px 0 10px;
        font-weight: bold;
        font-size: 14px;
      }

      .image-list {
        display: flex;
        flex-wrap: wrap;
        gap: 10px;

        .pro-image {
          width: 100px;
          height: 100px;
          cursor: pointer;
          border-radius: 4px;
        }
      }

      .sku-table {
        margin-top: 15px;
      }

      .product-text {
        margin-top: 15px;

        .text-content {
          max-height: 200px;
          overflow-y: auto;
          padding: 10px;
          border: 1px solid var(--el-border-color);
          border-radius: 4px;
        }
      }
    }
  }

  // 移除所有可能限制滚动的样式
  * {
    box-sizing: border-box;
  }

  .commodity-system-container {
    padding: 20px;
    overflow: visible !important;
    position: relative;
  }

  // 表格容器特殊处理
  .art-table {
    margin-top: 20px;
    position: relative;
    width: 100%;
  }

  // 为分页组件创建专用的滚动容器
  .pagination-scroll-wrapper {
    display: block !important;
    width: 100% !important;
    overflow-x: auto !important;
    overflow-y: visible !important;
    white-space: nowrap !important;
    -webkit-overflow-scrolling: touch !important;
    scroll-behavior: smooth !important;
    margin-top: 16px;
    position: relative;
  }

  // 分页组件核心样式
  .pagination-scroll-wrapper .table-pagination {
    display: inline-flex !important;
    justify-content: flex-start !important;
    padding: 0 !important;
    margin: 0 !important;
    min-width: 100% !important;
    width: auto !important;
  }

  // 确保 El-Pagination 组件可以正常滚动
  .pagination-scroll-wrapper .el-pagination {
    display: inline-flex !important;
    width: auto !important;
    flex-wrap: nowrap !important;
  }

  // 移除所有固定定位的影响
  .art-table :deep(.el-table__fixed-right),
  .art-table :deep(.el-table__fixed) {
    position: relative !important;
    right: 0 !important;
    left: 0 !important;
    height: auto !important;
  }

  // 响应式适配
  @media screen and (max-width: 768px) {
    .commodity-system-container {
      padding: 10px;

      .search-form {
        padding: 10px;

        .el-form-item {
          width: 100%;
          margin-bottom: 10px;
        }

        .el-input,
        .el-select {
          width: 100% !important;
        }
      }

      .product-info {
        flex-direction: column;
        align-items: flex-start;

        .product-image {
          margin-bottom: 5px;
        }
      }

      .table-actions {
        flex-direction: column;
        gap: 5px;
      }

      .product-detail {
        .image-list {
          .pro-image {
            width: 80px;
            height: 80px;
          }
        }
      }
    }
  }

  // 显示滚动条以明确指示可滚动
  .pagination-scroll-wrapper::-webkit-scrollbar {
    height: 6px;
    background: #f0f0f0;
  }
  .pagination-scroll-wrapper::-webkit-scrollbar-thumb {
    background: #c0c4cc;
    border-radius: 3px;
  }
  .pagination-scroll-wrapper::-webkit-scrollbar-thumb:hover {
    background: #909399;
  }
</style>
